<template>
	<div class="sys-user-container">
		<splitpanes class="default-theme">
			<pane size="20">
				<OrgTree ref="orgTreeRef" @node-click="nodeClick" />
			</pane>
			<pane size="80" style="overflow: auto;">
				<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
					<el-form :model="state.queryParams" ref="queryForm" :inline="true">
							<el-form-item :label="$t('system.user.account')">
								<el-input v-model="state.queryParams.account" :placeholder="$t('system.user.account')" clearable />
							</el-form-item>
							<el-form-item :label="$t('system.user.realName')">
								<el-input v-model="state.queryParams.realName" :placeholder="$t('system.user.realName')" clearable />
							</el-form-item>
							<el-form-item :label="$t('system.user.posName')">
								<el-input v-model="state.queryParams.posName" :placeholder="$t('system.user.posName')" clearable />
							</el-form-item>
							<el-form-item :label="$t('system.user.phone')">
								<el-input v-model="state.queryParams.phone" :placeholder="$t('system.user.phone')" clearable />
							</el-form-item>
							<el-form-item>
								<el-button-group>
									<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'sysUser:page'"> {{ $t('system.btn.query') }} </el-button>
									<el-button icon="ele-Refresh" @click="resetQuery"> {{ $t('system.btn.reset') }} </el-button>
								</el-button-group>
							</el-form-item>
							<el-form-item>
								<el-button type="primary" icon="ele-Plus" @click="openAddUser" v-auth="'sysUser:addUser'"> {{ $t('system.btn.add') }} </el-button>
							</el-form-item>
						</el-form>
				</el-card>

				<el-card class="full-table" shadow="hover" style="margin-top: 5px">
					<el-table :data="state.userData" style="width: 100%" v-loading="state.loading" border>
						<el-table-column type="index" :label="$t('system.user.index')" width="55" align="center" fixed />
						<el-table-column :label="$t('system.user.avatar')" width="80" align="center" show-overflow-tooltip>
							<template #default="scope">
								<el-avatar :src="scope.row.avatar" size="small">{{ scope.row.nickName?.slice(0, 1) ?? scope.row.realName?.slice(0, 1) }} </el-avatar>
							</template>
						</el-table-column>
						<el-table-column prop="account" :label="$t('system.user.account')" width="120" align="center" show-overflow-tooltip />
						<!-- <el-table-column prop="nickName" label="昵称" width="120" align="center" show-overflow-tooltip /> -->
						<el-table-column prop="realName" :label="$t('system.user.realName')" width="120" align="center" show-overflow-tooltip />
						<el-table-column prop="phone" :label="$t('system.user.phone')" width="120" align="center" show-overflow-tooltip />
						<!-- <el-table-column label="出生日期" width="100" align="center" show-overflow-tooltip>
							<template #default="scope">
								{{ formatDate(new Date(scope.row.birthday), 'YYYY-mm-dd') }}
							</template>
						</el-table-column>
						<el-table-column :label="$t('system.user.gender')" width="70" align="center" show-overflow-tooltip>
							<template #default="scope">
								<el-tag v-if="scope.row.sex === 1" type="success">{{ $t('system.user.male') }}</el-tag>
								<el-tag v-else-if="scope.row.sex === 2" type="danger">{{ $t('system.user.female') }}</el-tag>
								<el-tag v-else-if="scope.row.sex === 0" type="info">{{ $t('system.user.unknown') }}</el-tag>
								<el-tag v-else-if="scope.row.sex === 9" type="info">{{ $t('system.user.unstated') }}</el-tag>
							</template>
						</el-table-column> -->
						<el-table-column :label="$t('system.user.adminType')" width="110" align="center" show-overflow-tooltip>
							<template #default="scope">
                				<g-sys-dict v-model="scope.row.adminType" code="AccountTypeEnum" />
							</template>
						</el-table-column>
						<el-table-column prop="roleName" :label="$t('system.user.roleName')" min-width="150" align="center" show-overflow-tooltip />
						<el-table-column prop="orgName" :label="$t('system.user.orgName')" min-width="120" align="center" show-overflow-tooltip />
						<el-table-column prop="posName" :label="$t('system.user.posName')" min-width="120" align="center" show-overflow-tooltip />
						<el-table-column :label="$t('system.user.status')" width="120" align="center" show-overflow-tooltip>
						<template #default="scope">
							<div style="display: flex; align-items: center; justify-content: center;">
								<el-switch 
									v-model="scope.row.isDisable" 
									:active-value="0" 
									:inactive-value="1" 
									size="small"  
									@change="changeStatus(scope.row)" 
									v-auth="'sysUser:setStatus'" 
								/>
								<span style="margin-left: 8px;">
									{{ scope.row.isDisable === 0 ? $t('system.user.enable') : $t('system.user.disable') }}
								</span>
							</div>
						</template>
					</el-table-column>
						<el-table-column :label="$t('system.user.modifyRecord')" width="100" align="center" show-overflow-tooltip>
							<template #default="scope">
								<ModifyRecord :data="scope.row" />
							</template>
						</el-table-column>
						<el-table-column :label="$t('system.user.operate')" width="360" align="center" fixed="right" show-overflow-tooltip>
							<template #default="scope">
								<el-tooltip :content="$t('system.btn.edit')" placement="top">
									<el-button icon="ele-Edit" text type="primary" v-auth="'sysUser:updateUser'" @click="openEditUser(scope.row)"> </el-button>
								</el-tooltip>
								<el-button icon="ele-Menu" size="small" text type="primary" @click="openGrantRole(scope.row)" v-auth="'sysUser:grantRole'"> {{ $t('system.btn.grantRole') }} </el-button>
								<el-tooltip :content="$t('system.user.copy')" placement="top">
									<el-button icon="ele-CopyDocument" text type="primary" v-auth="'sysUser:addUser'" @click="openCopyMenu(scope.row)"> </el-button>
								</el-tooltip>
								<el-button icon="ele-RefreshLeft" text type="danger" v-auth="'sysUser:resetPwd'" @click="resetUserPwd(scope.row)">{{ $t('system.btn.resetPwd') }}</el-button>
								<el-button icon="ele-Unlock" text type="primary" v-auth="'sysUser:unlockLogin'" @click="unlockLogin(scope.row)">{{ $t('system.btn.unlockLogin') }}</el-button>
								<el-tooltip :content="$t('system.btn.delete')" placement="top">
									<el-button icon="ele-Delete" text type="danger" v-auth="'sysUser:deleteUser'" @click="delUser(scope.row)"> </el-button>
								</el-tooltip>
							</template>
						</el-table-column>
					</el-table>
					<el-pagination
						v-model:currentPage="state.tableParams.pageNo"
						v-model:page-size="state.tableParams.pageSize"
						:total="state.tableParams.total"
						:page-sizes="[10, 20, 50, 100]"
						size="small"
						background
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						layout="total, sizes, prev, pager, next, jumper"
					/>
				</el-card>
			</pane>
		</splitpanes>

		<EditUser ref="editUserRef" :title="state.editUserTitle" :orgData="state.orgTreeData" @handleQuery="handleQuery" />
		<GrantRole ref="grantRoleRef" :title="state.editUserTitle" @handleQuery="handleQuery" />
	</div>
</template>

<script lang="ts" setup name="sysUser">
import { onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessageBox, ElMessage } from 'element-plus';
import OrgTree from '/@/views/system/organization/component/orgTree.vue';
import EditUser from '/@/views/system/user/component/editUser.vue';
import GrantRole from '/@/views/system/user/component/grantRole.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import CallBar from '/@/components/callTel/callBar.vue';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';

import { apiSysOrgListGet, apiSysUserPagePost,apiSysUserDeletePost,apiSysUserSetStatusPost,apiSysUserResetPwdPost,apiSysUserUnlockLoginPost } from '/@/api-services/api';

const orgTreeRef = ref<InstanceType<typeof OrgTree>>();
const editUserRef = ref<InstanceType<typeof EditUser>>();
const grantRoleRef = ref<InstanceType<typeof GrantRole>>();
const { t } = useI18n();
const state = reactive({
	loading: false,
	userData: [] as Array<any>,
	orgTreeData: [] as Array<any>,
	queryParams: {
		orgId: -1,
		account: undefined,
		realName: undefined,
		phone: undefined,
		posName: undefined
	}, 
	tableParams: {
		pageNo: 1,
		pageSize: 50,
		total: 0 as any,
	},
	editUserTitle: '',
});

onMounted(async () => {
	await loadOrgData();
	await handleQuery();
});

// 查询机构数据
const loadOrgData = async () => {
	state.loading = true;
	let res = await apiSysOrgListGet(0);
	state.orgTreeData = res.data.data ?? [];
	state.loading = false;
};

// 查询操作
const handleQuery = async () => {
	state.loading = true;
	let params = Object.assign(state.queryParams, state.tableParams);
	let res = await apiSysUserPagePost(params);
	state.userData = res.data.data?.rows ?? [];
	state.tableParams.total = res.data.data?.totalRows;
	state.loading = false;
};

// 重置操作
const resetQuery = async () => {
	state.queryParams.orgId = -1;
	state.queryParams.account = undefined;
	state.queryParams.realName = undefined;
	state.queryParams.phone = undefined;
	state.queryParams.posName = undefined;
	await handleQuery();
};

// 打开新增页面
const openAddUser = () => {
	state.editUserTitle = t('system.user.addUser');
	editUserRef.value?.openDialog({ id: undefined, birthday: '2000-01-01', sex: 1, sort: 100, cardType: 0, cultureLevel: 5,adminType:0,isDisable:0 });
};

// 打开编辑页面
const openEditUser = (row: any) => {
	state.editUserTitle = t('system.user.editUser');
	editUserRef.value?.openDialog(row);
};

//分配角色
const openGrantRole = (row: any) => {
	state.editUserTitle = t('system.user.grantRole');
	grantRoleRef.value?.openDialog(row);
};
// 打开复制页面
const openCopyMenu = (row: any) => {
	state.editUserTitle = t('system.user.copyUser');
	var copyRow = JSON.parse(JSON.stringify(row)) as any;
	copyRow.id = 0;
	copyRow.account = '';
	editUserRef.value?.openDialog(copyRow);
};

// 删除
const delUser = (row: any) => {
	ElMessageBox.confirm(`确定删除账号：【${row.account}】?`, t('message.tips'), {
		confirmButtonText: t('message.confirm'),
		cancelButtonText: t('message.cancel'),
		type: 'warning',
	})
		.then(async () => {
			await apiSysUserDeletePost({ id: row.id });
			await handleQuery();
			ElMessage.success(t('system.user.deleteSuccess'));
		})
		.catch(() => {});
};

// 改变页面容量
const handleSizeChange = (val: number) => {
	state.tableParams.pageSize = val;
	handleQuery();
};

// 改变页码序号
const handleCurrentChange = async (val: number) => {
	state.tableParams.pageNo = val;
	await handleQuery();
};

// 修改状态
const changeStatus = async (row: any) => {
	await apiSysUserSetStatusPost({ id: row.id, isDisable: row.isDisable })
		.then(() => {
			ElMessage.success(t('system.user.accountStatusSetSuccess'));
		})
		.catch(() => {
			row.isDisable = row.isDisable == 1 ? 0 : 1;
		});
};

// 重置密码
const resetUserPwd = async (row: any) => {
	ElMessageBox.confirm(`确定重置密码：【${row.account}】?`, t('message.tips'), {
		confirmButtonText: t('message.confirm'),
		cancelButtonText: t('message.cancel'),
		type: 'warning',
	})
		.then(async () => {
			await apiSysUserResetPwdPost({ id: row.id })
				.then((res) => {
					ElMessage.success(t('system.user.resetPwdSuccess', { password: res.data.data }));
				});
		})
		.catch(() => {});
};

// 解除登录锁定
const unlockLogin = async (row: any) => {
	ElMessageBox.confirm(`确定解除登录锁定：【${row.account}】?`, t('message.tips'), {
		confirmButtonText: t('message.confirm'),
		cancelButtonText: t('message.cancel'),
		type: 'warning',
	})
		.then(async () => {
			await apiSysUserUnlockLoginPost({ id: row.id })
				.then(() => {
					ElMessage.success(t('system.user.unlockLoginSuccess'));
				});
		})
		.catch(() => {});
};

// 树组件点击
const nodeClick = async (node: any) => {
	state.queryParams.orgId = node.id;
	state.queryParams.account = undefined;
	state.queryParams.realName = undefined;
	state.queryParams.phone = undefined; 
	await handleQuery();
};
</script>
